var server = "http://security.jelastic.servint.net/";
server += "webresources/hash/";

var imageLoader = new Image();
imageLoader.src = "images/loader.gif";

$(function() {
  console.info("DOM Ready!");
  
  if ($("#data")) {
    $("#data").focus();
  }
  
  $("#hashForm").submit(function() {
    sendHashRequest(this);
    return false;
  });
});

var jqxhr = null;

function sendHashRequest(form) {  
  if (jqxhr !== null) {
    var answer = confirm("Do you want to cancel the previous request?");

    if (answer) {
      jqxhr.abort();
      $("#board").html("");
    }

  }

  var algorithm = $("#algorithm").val();
  var url = null;

  if (algorithm !== null && algorithm.length > 0) {
    url = server + algorithm;
  }

  var data = $("#data").val();
  data = Base64.encode(data);
  var request = {"data": data};

  jqxhr = $.ajax({
    type: "post",
    url: url,
    data: JSON.stringify(request),
    contentType: "application/json",
    beforeSend: function() {
      $("#board").html("<img src='images/loader.gif' alt='Loading' />");
    }
  }).done(function(response) {
    $("#hash").val(response.data);
    try {
      $("#hashHex").val(base64ToHex(response.data));
    } catch (e) {
      $("#hashHex").val("");
    }
    $("#board").html("");
  }).fail(function() {
    $("#board").html("<span class='error'>Can not connect to the server!</span>");
  }).always(function() {
    jqxhr = null;
  });
}
